#include "Parser.hpp"

using namespace std;

Parser::Parser(string fileUrl)
{
	this->file=new ifstream;
	this->file->open(fileUrl.c_str());
		
	if (!this->file->is_open())
		cerr << "Couldn't read file" << endl;
	else
	{
		this->parseTasks();
		this->file->close();
	}
}

void Parser::parseTasks()
{
	bool end=false;
	while(!end)
	{
		nextToken();

		if(elements.size()>0)
		{
			if (StringUtils::trimAll(elements.at(0))=="TachePeriodique")
			{
				cout<<"TachePeriodique"<<endl;
				parsePeriodicTask();
			}
			if (StringUtils::trimAll(elements.at(0))=="Tache")
			{
				cout<<"Tache"<<endl;
				parseAperiodicTask();
			}
			if(token=="$")
				end=true;

			cout<<endl;
		}
	}
}

void Parser::parsePeriodicTask()
{
	int ci,di,pi;

	for(unsigned i=0;i<3;i++)
	{
		nextToken();
		if (StringUtils::trimAll(elements.at(0))=="Ci")
		{
			cout<<"Ci="<<elements.at(1)<<endl;
			ci = StringUtils::ParseInt(elements.at(1));
		}
		else
		if (StringUtils::trimAll(elements.at(0))=="Di")
		{
			cout<<"Di="<<elements.at(1)<<endl;
			di = StringUtils::ParseInt(elements.at(1));
		}
		else
		if (StringUtils::trimAll(elements.at(0))=="Pi")
		{
			cout<<"Pi="<<elements.at(1)<<endl;
			pi = StringUtils::ParseInt(elements.at(1));
		}
		else
		{
			i--;
		}
	}
	cout <<"TachePeriodique="<<ci<<","<<di<<","<<pi<<endl;
	parsedPeriodicTasks.push_back(TachePeriodique(ci,pi,di));
}

void Parser::parseAperiodicTask()
{
	int ci,di;

	for(unsigned i=0;i<2;i++)
	{
		nextToken();
		if (StringUtils::trimAll(elements.at(0))=="Ci")
		{
			cout<<"Ci="<<elements.at(1)<<endl;
			ci = StringUtils::ParseInt(elements.at(1));
		}
		else
		if (StringUtils::trimAll(elements.at(0))=="Di")
		{
			cout<<"Di="<<elements.at(1)<<endl;
			di = StringUtils::ParseInt(elements.at(1));
		}
		else
		{
			i--;
		}
	}
	parsedAperiodicTasks.push_back(TacheAperiodique(ci,di));
	cout <<"Tache="<<ci<<","<<di<<endl;
}

void Parser::nextToken()
{
	char temp[1024];
	file->getline(temp, 1024);
	
	token = temp;	
	elements = StringUtils::explode(":",token);
}